{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "0276124b",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "PreTrainedTokenizer(name_or_path='bert-base-chinese', vocab_size=21128, model_max_len=512, is_fast=False, padding_side='right', truncation_side='right', special_tokens={'unk_token': '[UNK]', 'sep_token': '[SEP]', 'pad_token': '[PAD]', 'cls_token': '[CLS]', 'mask_token': '[MASK]'})"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第2章/加载编码工具\n",
    "from transformers import BertTokenizer\n",
    "\n",
    "tokenizer = BertTokenizer.from_pretrained(\n",
    "    pretrained_model_name_or_path='bert-base-chinese',\n",
    "    cache_dir=None,\n",
    "    force_download=False,\n",
    ")\n",
    "\n",
    "tokenizer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e80e864e",
   "metadata": {},
   "outputs": [],
   "source": [
    "#第2章/准备实验数据\n",
    "sents = [\n",
    "    '你站在桥上看风景',\n",
    "    '看风景的人在楼上看你',\n",
    "    '明月装饰了你的窗子',\n",
    "    '你装饰了别人的梦',\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "cd216567",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 872, 4991, 1762, 3441, 677, 4692, 7599, 3250, 102, 4692, 7599, 3250, 4638, 782, 1762, 3517, 677, 4692, 872, 102, 0, 0, 0, 0]\n",
      "[CLS] 你 站 在 桥 上 看 风 景 [SEP] 看 风 景 的 人 在 楼 上 看 你 [SEP] [PAD] [PAD] [PAD] [PAD]\n"
     ]
    }
   ],
   "source": [
    "#第2章/基本的编码函数\n",
    "out = tokenizer.encode(\n",
    "    text=sents[0],\n",
    "    text_pair=sents[1],\n",
    "\n",
    "    #当句子长度大于max_length时截断\n",
    "    truncation=True,\n",
    "\n",
    "    #一律补pad到max_length长度\n",
    "    padding='max_length',\n",
    "    add_special_tokens=True,\n",
    "    max_length=25,\n",
    "    return_tensors=None,\n",
    ")\n",
    "\n",
    "print(out)\n",
    "print(tokenizer.decode(out))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "db6501e4",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_ids : [101, 872, 4991, 1762, 3441, 677, 4692, 7599, 3250, 102, 4692, 7599, 3250, 4638, 782, 1762, 3517, 677, 4692, 872, 102, 0, 0, 0, 0]\n",
      "token_type_ids : [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]\n",
      "special_tokens_mask : [1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]\n",
      "attention_mask : [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]\n",
      "length : 25\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 你 站 在 桥 上 看 风 景 [SEP] 看 风 景 的 人 在 楼 上 看 你 [SEP] [PAD] [PAD] [PAD] [PAD]'"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第2章/进阶的编码函数\n",
    "out = tokenizer.encode_plus(\n",
    "    text=sents[0],\n",
    "    text_pair=sents[1],\n",
    "\n",
    "    #当句子长度大于max_length时截断\n",
    "    truncation=True,\n",
    "\n",
    "    #一律补零到max_length长度\n",
    "    padding='max_length',\n",
    "    max_length=25,\n",
    "    add_special_tokens=True,\n",
    "\n",
    "    #可取值tf,pt,np,默认为返回list\n",
    "    return_tensors=None,\n",
    "\n",
    "    #返回token_type_ids\n",
    "    return_token_type_ids=True,\n",
    "\n",
    "    #返回attention_mask\n",
    "    return_attention_mask=True,\n",
    "\n",
    "    #返回special_tokens_mask 特殊符号标识\n",
    "    return_special_tokens_mask=True,\n",
    "\n",
    "    #返回length 标识长度\n",
    "    return_length=True,\n",
    ")\n",
    "\n",
    "#input_ids 编码后的词\n",
    "#token_type_ids 第一个句子和特殊符号的位置是0,第二个句子的位置是1\n",
    "#special_tokens_mask 特殊符号的位置是1,其他位置是0\n",
    "#attention_mask pad的位置是0,其他位置是1\n",
    "#length 返回句子长度\n",
    "for k, v in out.items():\n",
    "    print(k, ':', v)\n",
    "\n",
    "tokenizer.decode(out['input_ids'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "23da78fc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "input_ids : [[101, 872, 4991, 1762, 3441, 677, 4692, 7599, 3250, 102, 4692, 7599, 3250, 4638, 782, 1762, 3517, 677, 4692, 872, 102, 0, 0, 0, 0], [101, 3209, 3299, 6163, 7652, 749, 872, 4638, 4970, 2094, 102, 872, 6163, 7652, 749, 1166, 782, 4638, 3457, 102, 0, 0, 0, 0, 0]]\n",
      "token_type_ids : [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]]\n",
      "special_tokens_mask : [[1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]]\n",
      "length : [21, 20]\n",
      "attention_mask : [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 你 站 在 桥 上 看 风 景 [SEP] 看 风 景 的 人 在 楼 上 看 你 [SEP] [PAD] [PAD] [PAD] [PAD]'"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第2章/批量编码成对的句子\n",
    "out = tokenizer.batch_encode_plus(\n",
    "    #编码成对的句子\n",
    "    batch_text_or_text_pairs=[(sents[0], sents[1]), (sents[2], sents[3])],\n",
    "    \n",
    "    add_special_tokens=True,\n",
    "\n",
    "    #当句子长度大于max_length时截断\n",
    "    truncation=True,\n",
    "\n",
    "    #一律补零到max_length长度\n",
    "    padding='max_length',\n",
    "    max_length=25,\n",
    "\n",
    "    #可取值tf,pt,np,默认为返回list\n",
    "    return_tensors=None,\n",
    "\n",
    "    #返回token_type_ids\n",
    "    return_token_type_ids=True,\n",
    "\n",
    "    #返回attention_mask\n",
    "    return_attention_mask=True,\n",
    "\n",
    "    #返回special_tokens_mask 特殊符号标识\n",
    "    return_special_tokens_mask=True,\n",
    "\n",
    "    #返回offset_mapping 标识每个词的起止位置,这个参数只能BertTokenizerFast使用\n",
    "    #return_offsets_mapping=True,\n",
    "\n",
    "    #返回length 标识长度\n",
    "    return_length=True,\n",
    ")\n",
    "\n",
    "#input_ids 编码后的词\n",
    "#token_type_ids 第一个句子和特殊符号的位置是0,第二个句子的位置是1\n",
    "#special_tokens_mask 特殊符号的位置是1,其他位置是0\n",
    "#attention_mask pad的位置是0,其他位置是1\n",
    "#length 返回句子长度\n",
    "for k, v in out.items():\n",
    "    print(k, ':', v)\n",
    "\n",
    "tokenizer.decode(out['input_ids'][0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "390006f3",
   "metadata": {},
   "outputs": [],
   "source": [
    "#编码单个的句子\n",
    "#batch_text_or_text_pairs=[sents[0], sents[1]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "6e7b23d7",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(dict, 21128, False)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第2章/获取字典\n",
    "vocab = tokenizer.get_vocab()\n",
    "\n",
    "type(vocab), len(vocab), '明月' in vocab"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "52a69eb1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(dict, 21132, 21128, 21131)"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第2章/添加新词\n",
    "tokenizer.add_tokens(new_tokens=['明月', '装饰', '窗子'])\n",
    "\n",
    "tokenizer.add_special_tokens({'eos_token': '[EOS]'})\n",
    "\n",
    "vocab = tokenizer.get_vocab()\n",
    "\n",
    "type(vocab), len(vocab), vocab['明月'], vocab['[EOS]']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "989bf968",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[101, 21128, 21129, 749, 872, 4638, 21130, 21131, 102, 0]\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'[CLS] 明月 装饰 了 你 的 窗子 [EOS] [SEP] [PAD]'"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#第2章/编码新添加的词\n",
    "out = tokenizer.encode(\n",
    "    text='明月装饰了你的窗子[EOS]',\n",
    "    text_pair=None,\n",
    "\n",
    "    #当句子长度大于max_length时,截断\n",
    "    truncation=True,\n",
    "\n",
    "    #一律补pad到max_length长度\n",
    "    padding='max_length',\n",
    "    add_special_tokens=True,\n",
    "    max_length=10,\n",
    "    return_tensors=None,\n",
    ")\n",
    "\n",
    "print(out)\n",
    "\n",
    "tokenizer.decode(out)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
